package vn.game;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.Gallery;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainPlayActivity extends Activity implements CrosswordLayout.OnTouchEditText {

	private String tag = MainPlayActivity.class.getSimpleName();
	private CrosswordPagerAdapter crosswordPagerAdapter;
	private ViewPager crosswordViewPager;

	// Timer
	TextView tvDisplayTime;
	private int hour = 0;
	private int minute = 0;
	private int second = 0;
	private Handler _myHandler;
	private Runnable _myTask;
	// ////////////

	// /play
	LinearLayout llCenter;
	public static int widthScreen = 300;
	private TextView tvHint, tvAcross;
	// /////////////////

	FrameLayout frameLayout;
	LinearLayout llDown, llAcross;

	CrosswordHintArrayAdapter acrossAdapter = null, downAdapter = null;
	CrosswordLayout playLayout = null;
	Gallery.LayoutParams lp;
	public PlayGame playGame = null;

	ProcessDialogCrosswrod pd;

	ViewConfiguration vc;
	static int SWIPE_MAX_OFF_PATH = 250;
	static int SWIPE_MIN_DISTANCE = 100;
	static int SWIPE_THRESHOLD_VELOCITY = 100;

	static boolean acrossText = false;
	static int row = -1, column = -1;
	static int randGame = -1;

	// private GestureDetector gestureDetector;
	// View.OnTouchListener gestureListener;

	// private int pageSelected = 1;

	// ProgressDialog progress;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		// final ProgressDialog progress = new ProgressDialog(this);
		setContentView(R.layout.play_pageview);

		try {
			Log.i(tag, "onCreate...");

			crosswordViewPager = (ViewPager) findViewById(R.id.playPager);
			tvDisplayTime = (TextView) findViewById(R.id.tvDisplayTime);

			// get width of screen
			Display display = getWindowManager().getDefaultDisplay();
			widthScreen = display.getWidth();

			// ///////////
			vc = ViewConfiguration.get(this);
			SWIPE_MIN_DISTANCE = vc.getScaledTouchSlop();
			SWIPE_THRESHOLD_VELOCITY = vc.getScaledMinimumFlingVelocity();
			// /////////

			// pagelistener is just for getting selected page
			crosswordViewPager.setOnPageChangeListener(new OnPageChangeListener() {

				@Override
				public void onPageSelected(int position) {
					// pageSelected = position;
					Log.i(tag, "onPageSelected: " + position);
				}

				@Override
				public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
					// Log.i(tag, "onPageScrolled:  pos:" + position + ", positionOffset: " + positionOffset + "; positionOffsetPixels: "
				}

				@Override
				public void onPageScrollStateChanged(int state) {
					// Log.i(tag, "onPageScrollStateChanged: " + state);
				}

			});

			pd = new ProcessDialogCrosswrod();
			pd.execute(this);

			Log.i(tag, "onCreate...finish");

		} catch (Exception ex) {
			Log.e(tag, "onCreate() Error: " + ex);
		}
	}

	private void newGame() {
		Log.i(tag, "Neu game");
		playLayout = null;
		acrossAdapter = null;
		downAdapter = null;
		try {

			second = 0;
			minute = 0;
			hour = 0;
			playGame.CloseDB();
			playGame.Init();
			crosswordPagerAdapter = new CrosswordPagerAdapter(this);
			// crosswordViewPager.removeViewInLayout(llCenter);
			// crosswordViewPager.removeViewInLayout(llAcross);
			// crosswordViewPager.removeViewInLayout(llDown);

			if (MainPlayActivity.column <= 0) {
				cancelTimer();
				Toast.makeText(this, "Data not found!!!!", Toast.LENGTH_LONG).show();
				Log.i(tag, "reCreateLayout() data not found");
				return;
			}

			llAcross.removeAllViews();
			llCenter.removeAllViews();
			llDown.removeAllViews();

			reCreateLayout(this);

			llAcross.refreshDrawableState();
			llDown.refreshDrawableState();

			// llAcross.notify();
			crosswordViewPager.setAdapter(crosswordPagerAdapter);
			crosswordViewPager.setCurrentItem(1);

//			// Timer
//			cancelTimer();
//			_myTask = new MyTimerTask();
//			_myHandler = new Handler();
//			_myHandler.postDelayed(_myTask, 1000);

		} catch (Exception ex) {
			Log.e(tag, " newGame() Error: " + ex);
		}

	}
	
	

	// create layout
	public void reCreateLayout(Activity activity) {
		ListView lstDown, lstAcross;
		TextView tv;
		Log.i(tag, "Load layout");

		// center
		playLayout = new CrosswordLayout(activity, playGame);
		playLayout.SetOnTouchEdit(this);
		lp = new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		playLayout.setLayoutParams(lp);
		// playLayout.setBackgroundColor(Color.YELLOW);
		playLayout.setGravity(Gravity.CENTER_HORIZONTAL);

		// Layout play game
		frameLayout = new FrameLayout(activity);
		lp = new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		frameLayout.setLayoutParams(lp);
		frameLayout.addView(playLayout);

		llCenter.setOrientation(LinearLayout.VERTICAL);
		lp = new Gallery.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		llCenter.setLayoutParams(lp);
		llCenter.addView(frameLayout);
		llCenter.addView(createHint(activity));

		// /////////across
		acrossAdapter = new CrosswordHintArrayAdapter(activity, playGame.acrossHints);
		lstAcross = new ListView(activity);
		lstAcross.setAdapter(acrossAdapter);

		tv = new TextView(activity);
		tv.setText("Across");
		tv.setTextSize(20f);

		lstAcross.setLayoutParams(lp);
		llAcross.addView(tv);
		llAcross.addView(lstAcross);
		llAcross.setOrientation(LinearLayout.VERTICAL);

		// /////////down
		downAdapter = new CrosswordHintArrayAdapter(activity, playGame.downHints);
		lstDown = new ListView(activity);
		lstDown.setAdapter(downAdapter);

		tv = new TextView(activity);
		tv.setText("Down");
		tv.setTextSize(20f);

		llDown.setLayoutParams(lp);
		llDown.addView(tv);
		llDown.addView(lstDown);
		llDown.setOrientation(LinearLayout.VERTICAL);

		// return null;
	}

	public LinearLayout createHint(Activity activity) {

		LinearLayout ll = new LinearLayout(activity);
		ll.setOrientation(LinearLayout.VERTICAL);
		lp = new Gallery.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		ll.setLayoutParams(lp);
		// ll.setGravity(View.)

		// create textview across
		tvAcross = new TextView(activity);
		tvAcross.setText("Across");
		tvAcross.setPadding(0, 15, 0, 10);
		tvAcross.setLayoutParams(lp);
		tvAcross.setTextSize(20f);
		ll.addView(tvAcross);

		tvHint = new TextView(activity);
		// tvHint.setId(1101);
		tvHint.setPadding(10, 0, 0, 0);
		tvHint.setText("");
		tvHint.setTypeface(Typeface.DEFAULT_BOLD);
		tvHint.setLayoutParams(lp);
		ll.addView(tvHint);

		// Set Hint
		SetOnTouch(1);

		return ll;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		try {
			cancelTimer();
			playGame.CloseDB();

		} catch (Exception ex) {
			Log.e(tag + "onDestroy()", "Error: " + ex.getMessage());
		}
	}

	/* Initiating Menu XML file (menu.xml) */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.layout.menu_playgame, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.mnSubmit:
			if (playGame.checkWord()) {
				cancelTimer();
				Toast.makeText(getBaseContext(), "Congratulations!!!!", Toast.LENGTH_SHORT).show();
			} else
				Toast.makeText(getBaseContext(), "Not correct!!!!!", Toast.LENGTH_SHORT).show();

			return true;
		case R.id.mnHint:
			// playGame.loadGird(true);
			playLayout.loadGird(true);

			return true;
		case R.id.mnNew:
			// new game
			new ProcessDialogCrosswrodNewGame().execute(this);			
//			newGame();
			return true;
			// case R.id.mnCreate:
			// // ///////////
			// Intent createGame = new Intent(MainPlayActivity.this, CreateGame.class);
			// startActivity(createGame);
			// return true;
		default:
			return super.onOptionsItemSelected(item);

		}

	}

	private class CrosswordPagerAdapter extends PagerAdapter {
		Activity activity;

		public CrosswordPagerAdapter(Activity activity) {
			this.activity = activity;
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			// Log.i(tag, "destroyItem");

		}

		@Override
		public void finishUpdate(View arg0) {
			// TODO Auto-generated method stub
			// Log.i(tag,"finishUpdate");
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return 3;
		}

		@Override
		public Object instantiateItem(View collection, int position) {

			ListView lstDown, lstAcross;
			TextView tv;
			Log.i(tag, "instantiateItem position:" + position);
			// TextView tv = null;
			if (position == 1) {
				// Center
				if (playLayout == null) {
					Log.i(tag, "Load adapter center");
					lp = new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

					playLayout = new CrosswordLayout(activity, playGame);
					playLayout.SetOnTouchEdit((CrosswordLayout.OnTouchEditText) activity);
					playLayout.setLayoutParams(lp);
					// playLayout.setBackgroundColor(Color.YELLOW);
					playLayout.setGravity(Gravity.CENTER_HORIZONTAL);

					lp = new Gallery.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);

					// Layout play game
					llCenter = new LinearLayout(activity);
					llCenter.setLayoutParams(lp);
					llCenter.setOrientation(LinearLayout.VERTICAL);

					frameLayout = new FrameLayout(activity);
					// frameLayout.setBackgroundColor(Color.GRAY);
					frameLayout.setLayoutParams(lp);
					frameLayout.addView(playLayout);

					llCenter.addView(frameLayout);
					llCenter.addView(createHint(activity));

					((ViewPager) collection).addView(llCenter, 0);
				}
				return llCenter;
			} else if (position == 0) {
				// Across
				if (acrossAdapter == null) {
					Log.i(tag, "Load adapter across size: " + playGame.acrossHints.size());
					try {
						acrossAdapter = new CrosswordHintArrayAdapter(activity, playGame.acrossHints);
						lstAcross = new ListView(activity);
						lstAcross.setAdapter(acrossAdapter);

						llAcross = new LinearLayout(activity);
						tv = new TextView(activity);
						tv.setText("Across");
						tv.setTextSize(20f);
						llAcross.addView(tv);
						llAcross.addView(lstAcross);
						llAcross.setOrientation(LinearLayout.VERTICAL);
						// llAcross.setBackgroundColor(Color.BLUE);

						((ViewPager) collection).addView(llAcross, 0);
					} catch (Exception ex) {
						Log.e(tag, "getView() Error: " + ex);
					}
				}
				return llAcross;
			} else if (position == 2) {
				// /Down
				if (downAdapter == null) {
					Log.i(tag, "Load adapter down size: " + playGame.acrossHints.size());
					downAdapter = new CrosswordHintArrayAdapter(activity, playGame.downHints);
					lstDown = new ListView(activity);
					lstDown.setAdapter(downAdapter);

					llDown = new LinearLayout(activity);
					tv = new TextView(activity);
					tv.setText("Down");
					tv.setTextSize(20f);
					llDown.addView(tv);
					llDown.addView(lstDown);
					llDown.setOrientation(LinearLayout.VERTICAL);
					// llDown.setBackgroundColor(Color.BLUE);

					((ViewPager) collection).addView(llDown, 0);
				}
				return llDown;

			} else
				return null;

			// return tv;
		}

		@Override
		public boolean isViewFromObject(View view, Object obj) {
			return view == (LinearLayout) obj;
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
			// TODO Auto-generated method stub

		}

		@Override
		public Parcelable saveState() {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
			// TODO Auto-generated method stub

		}

	}

	@Override
	public void SetOnTouch(int num) {
		Log.i(tag, "SetOnTouch() num: " + num);
		// for(int i : playGame.acrossHint){
		for (int i = 0; i < playGame.acrossHint.size(); i++) {
			if (num == playGame.acrossHint.get(i)) {
				Log.i(tag, "SetOnTouch() num: " + i + ", " + playGame.acrossHints.get(i));
				tvAcross.setText("Across:");
				tvHint.setText(playGame.acrossHints.get(i));
				return;
			}
		}

		for (int i = 0; i < playGame.downHint.size(); i++) {
			if (num == playGame.downHint.get(i)) {
				Log.i(tag, "SetOnTouch() num: " + i + ", " + playGame.downHints.get(i));
				tvAcross.setText("Down:");
				tvHint.setText(playGame.downHints.get(i));
				return;
			}
		}
	}

	public class ProcessDialogCrosswrod extends AsyncTask<Activity, Activity, String> {
		String tag = ProcessDialogCrosswrod.class.getSimpleName();
		Activity activity;
		MainPlayActivity mainActivity;
		private ProgressDialog progress = new ProgressDialog(MainPlayActivity.this);

		/**
		 * Showing the dialog on the UI thread.
		 */
		@Override
		protected void onPreExecute() {
			progress.setTitle("Crossword");
			progress.setMessage("Data loading.....");
			progress.setCancelable(false);
			progress.setIndeterminate(true);
			progress.show();
			Log.i(tag, "onPreExecute() finished");
		}

		@Override
		protected String doInBackground(Activity... params) {
			// TODO Auto-generated method stub
			try {
				Log.i(tag, "doInBackground....");
				// progress = ProgressDialog.show(params[0], "Crossword", "Creating data........", true);
				activity = params[0];
				// Thread.sleep(6250);
				playGame = new PlayGame(params[0]);
				// if (playGame.column > 0) {
				publishProgress(params[0]);
				// } else {
				// if (progress.isShowing())
				// progress.dismiss();
				// // Toast.makeText(params[0], "Data not found", Toast.LENGTH_LONG).show();
				// }

				Log.i(tag, "doInbackground() finished");
			} catch (Exception ex) {
				Log.e(tag, "doInbackgroud() Error: " + ex);
				if (progress.isShowing())
					progress.dismiss();
			}
			return null;
		}

		// -- called from the publish progress
		// -- notice that the datatype of the second param gets passed to this method
		@Override
		protected void onProgressUpdate(Activity... values) {
			super.onProgressUpdate(values);
			try {
				Log.i(tag, "onProgressUpdate.....");
				if (MainPlayActivity.column <= 0) {
					Toast.makeText(values[0], "Data not found", Toast.LENGTH_LONG).show();
					return;
				}
				crosswordPagerAdapter = new CrosswordPagerAdapter(values[0]);
				crosswordViewPager.setAdapter(crosswordPagerAdapter);
				crosswordViewPager.setCurrentItem(1);

				// Timer
				_myTask = new MyTimerTask();
				_myHandler = new Handler();
				_myHandler.postDelayed(_myTask, 1000);

			} catch (Exception ex) {
				if (progress.isShowing())
					progress.dismiss();
				Log.e(tag, "onProgressUpdate() Error: " + ex);
			}
		}

		/**
		 * When the task is completed, notifiy the Activity.
		 */
		@Override
		protected void onPostExecute(String unused) {
			Log.i(tag, "onPostExecute()....");
			if (progress.isShowing())
				progress.dismiss();
		}

	}
	
	
	
	//New Game
	public class ProcessDialogCrosswrodNewGame extends AsyncTask<Activity, Activity, String> {
		String tag = ProcessDialogCrosswrodNewGame.class.getSimpleName();
		Activity activity;
		MainPlayActivity mainActivity;
		private ProgressDialog progress = new ProgressDialog(MainPlayActivity.this);

		/**
		 * Showing the dialog on the UI thread.
		 */
		@Override
		protected void onPreExecute() {
			progress.setTitle("Crossword");
			progress.setMessage("Data loading.....");
			progress.setCancelable(false);
			progress.setIndeterminate(true);
			progress.show();
			Log.i(tag, "onPreExecute() finished");
		}

		@Override
		protected String doInBackground(Activity... params) {
			try {

//				newGame();
				publishProgress(params[0]);
				Log.i(tag, "doInbackground() finished");
			} catch (Exception ex) {
				Log.e(tag, "doInbackgroud() Error: " + ex);
				if (progress.isShowing())
					progress.dismiss();
			}
			return null;
		}

		// -- called from the publish progress
		// -- notice that the datatype of the second param gets passed to this method
		@Override
		protected void onProgressUpdate(Activity... values) {
			super.onProgressUpdate(values);
			try {
				Log.i(tag, "onProgressUpdate.....");
				newGame();
				// Timer
				cancelTimer();
				_myTask = new MyTimerTask();
				_myHandler = new Handler();
				_myHandler.postDelayed(_myTask, 1000);

			} catch (Exception ex) {
				if (progress.isShowing())
					progress.dismiss();
				Log.e(tag, "onProgressUpdate() Error: " + ex);
			}
		}

		/**
		 * When the task is completed, notifiy the Activity.
		 */
		@Override
		protected void onPostExecute(String unused) {
			Log.i(tag, "onPostExecute()....");
			if (progress.isShowing())
				progress.dismiss();
		}

	}
	

	// setup time
	private class MyTimerTask implements Runnable {
		public void run() {
			try {
				second++;
				if (second == 60) {
					second = 0;
					minute++;
					if (minute == 60) {
						minute = 0;
						hour++;
					}
				}

				tvDisplayTime.setText((hour > 9 ? hour : "0" + hour) + ":" + (minute > 9 ? minute : "0" + minute) + ":"
						+ (second > 9 ? second : "0" + second));
				_myHandler.postDelayed(this, 1000);
			} catch (Exception ex) {
				Log.e(tag + "MyTimerTask", "Error: " + ex.getMessage());
			}
		}
	}

	private void cancelTimer() {
		if (_myHandler != null) {
			_myHandler.removeCallbacks(_myTask);
			_myHandler = null;
			_myTask = null;
		}
	}

	// move page
	// class MyGestureDetector extends SimpleOnGestureListener {
	// private String tag = MyGestureDetector.class.getSimpleName();
	//
	// @Override
	// public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
	//
	// try {
	//
	// Log.i(tag, "onFling: x: " + e1.getX() + " || x2: " + e2.getX() + ";==== vX, vY: " + velocityX + "," + velocityX);
	//
	// if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
	// return false;
	// // right to left swipe
	// if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY && pageSelected == 2) {
	// Log.i(tag, "onFling: left");
	// crosswordViewPager.setCurrentItem(1);
	// } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY && pageSelected == 0) {
	// Log.i(tag, "onFling: right");
	// crosswordViewPager.setCurrentItem(1);
	// }
	//
	// } catch (Exception e) {
	// // nothing
	// }
	// return false;
	// }
	// }

}
